package com.wordpress.music2dot0.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Connection implements Runnable {
	private final String ENDTAG = "</data>";
	private GroupServer group;
	private final Socket socket;
	private final Scanner input;

	public Connection(Socket socket) throws IOException {
		this.socket = socket;
		this.input = new Scanner(new BufferedReader(new InputStreamReader(
				socket.getInputStream())));
		LoginServer.joinGroup(this);
	}

	public void joinGroup(GroupServer group) {
		this.group = group;
	}

	@Override
	public void run() {
		this.input.useDelimiter(this.ENDTAG);
		String inString;
		while (this.input.hasNext()) {
			inString = this.input.next().concat(this.ENDTAG); // wait for input
			LoginServer.log.finer("Message from "
					+ this.socket.getInetAddress() + ": " + inString);

			try {
				final DocumentBuilder documentBuilder = DocumentBuilderFactory
						.newInstance().newDocumentBuilder();
				final Document message = documentBuilder.parse(new InputSource(
						new StringReader(inString)));
				final Node contentNode = message.getDocumentElement()
						.getFirstChild();
				if (contentNode.getNodeName().equals("vote")) {
					this.group.vote(contentNode.getTextContent());
				}
				// TODO else if (contentNode.equals("group"))
			} catch (final ParserConfigurationException e) {
				e.printStackTrace();
			} catch (final SAXException e) {
				e.printStackTrace();
			} catch (final IOException e) {
				e.printStackTrace();
			}

		}

		/*
		 * Playlist.create("metal", 1);
		 * 
		 * try { // TODO Huidige stream sturen DocumentBuilderFactory
		 * documentBuilderFactory = DocumentBuilderFactory .newInstance();
		 * DocumentBuilder documentBuilder = documentBuilderFactory
		 * .newDocumentBuilder(); Document document =
		 * documentBuilder.newDocument(); Element message =
		 * document.createElement("message"); document.appendChild(message);
		 * Element currentSong = document.createElement("currentSong");
		 * message.appendChild(currentSong); Element url =
		 * document.createElement("url"); currentSong.appendChild(url); Text
		 * urlText = document
		 * .createTextNode("http://api.jamendo.com/get2/stream/track/redirect/"
		 * + "?id=667411&streamencoding=mp31"); url.appendChild(urlText);
		 * TransformerFactory tf = TransformerFactory.newInstance(); Transformer
		 * serializer = tf.newTransformer(); DOMSource source = new
		 * DOMSource(document); StreamResult result = new
		 * StreamResult(this.socket .getOutputStream());
		 * serializer.transform(source, result); // TODO Huidige playlist sturen
		 * } catch (ParserConfigurationException e) { // TODO Auto-generated
		 * catch block e.printStackTrace(); } catch
		 * (TransformerConfigurationException e) { // TODO Auto-generated catch
		 * block e.printStackTrace(); } catch (TransformerException e) { // TODO
		 * Auto-generated catch block e.printStackTrace(); } catch (IOException
		 * e) { // TODO Auto-generated catch block e.printStackTrace(); }
		 */
	}

	public void send(Document document) throws IOException {
		final TransformerFactory tf = TransformerFactory.newInstance();
		try {
			final Transformer serializer = tf.newTransformer();
			final DOMSource source = new DOMSource(document);
			final StreamResult result = new StreamResult(
					this.socket.getOutputStream());
			serializer.transform(source, result);
		} catch (final SocketException e) {
		} catch (final TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (final TransformerException e) {
			LoginServer.log.throwing("Connection", "send", e);
			LoginServer.log.info("Client disconnected.");
			this.socket.close();
		}
	}
}
